package cn.faifai.tagapi.utils;

import cn.faifai.tagapi.dto.PageQuery;
import org.springframework.data.domain.Page;

import java.lang.reflect.Field;

public class BeanUtil {
    public static void copyPropertiesNonNull(Object source, Object target) throws IllegalAccessException {
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(source);
            if (value != null && !(value instanceof String) || (value instanceof String && !((String) value).isEmpty())) {
                try {
                    Field targetField = target.getClass().getDeclaredField(field.getName());
                    targetField.setAccessible(true);
                    targetField.set(target, value);
                } catch (NoSuchFieldException e) {
                    // 目标对象中不存在的字段可以选择忽略或抛出异常
                }
            }
        }
    }

    public static PageQuery springPageToMinePage(Page source, PageQuery target){
        target.setPageNum(source.getNumber());
        target.setPageSize(source.getSize());
        target.setTotal(source.getTotalElements());
        target.setContents(source.getContent());
        target.setTotalPages(source.getTotalPages());
        return target;
    }
}
